import XLSX from 'xlsx';
var utils = {
    /*
        单位
    */
    units: '个十百千万@#%亿^&~',
    /*
      字符
  */
    chars: '零一二三四五六七八九',
};
utils.i18n = function (key, value) {
    return '';
};
utils.numberToChinese = function (number) {
    var a = (number + '').split('');


    var s = [];


    var t = this;
    if (a.length > 12) {
        throw new Error('too big');
    } else {
        for (var i = 0, j = a.length - 1; i <= j; i++) {
            if (j == 1 || j == 5 || j == 9) { // 两位数 处理特殊的 1*
                if (i == 0) {
                    if (a[i] != '1') s.push(t.chars.charAt(a[i]));
                } else {
                    s.push(t.chars.charAt(a[i]));
                }
            } else {
                s.push(t.chars.charAt(a[i]));
            }
            if (i != j) {
                s.push(t.units.charAt(j - i));
            }
        }
    }
    // return s;
    return s.join('').replace(/零([十百千万亿@#%^&~])/g, function (m, d, b) { // 优先处理 零百 零千 等
        b = t.units.indexOf(d);
        if (b != -1) {
            if (d == '亿') return d;
            if (d == '万') return d;
            if (a[j - b] == '0') return '零';
        }
        return '';
    }).replace(/零+/g, '零').replace(/零([万亿])/g, function (m, b) { // 零百 零千处理后 可能出现 零零相连的 再处理结尾为零的
        return b;
    }).replace(/亿[万千百]/g, '亿').replace(/[零]$/, '').replace(/[@#%^&~]/g, function (m) {
        return {
            '@': '十',
            '#': '百',
            '%': '千',
            '^': '十',
            '&': '百',
            '~': '千'
        }[m];
    }).replace(/([亿万])([一-九])/g, function (m, d, b, c) {
        c = t.units.indexOf(d);
        if (c != -1) {
            if (a[j - c] == '0') return d + '零' + b;
        }
        return m;
    });
};
utils.getLargeFormat = function (num, suffix = '、') {
    const value = Number(num);
    if (!isNaN(value)) {
        let result = '';
        const char = [
            '一',
            '二',
            '三',
            '四',
            '五',
            '六',
            '七',
            '八',
            '九'
        ];
        if (value > 0 && value < 10) {
            result = char[value - 1];
        } else if (value >= 10 && value < 100) {
            if (Math.floor(value / 10) === 1) {
                result += '十';
            } else {
                result += char[Math.floor(value / 10) - 1] + '十';
            }
            if (value % 10 > 0) {
                result += char[(value % 10) - 1];
            }
        }
        return result + suffix;
    } else {
        return '';
    }
};
utils.title = function (title) {
    title = title ? '同济大学-' + title : '同济大学-教学管理信息系统';
    window.document.title = title;
};

utils.setCookie = function (cname, cvalue, expire) {
    var d = new Date();
    d.setTime(expire || d.getTime() + (10 * 60 * 1000));
    var expires = 'expires=' + d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires + ';path=/';
};

utils.getCookie = function (cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return '';
};

var _fill = function (options, type, data, addAll) {
    options[type] = [];
    if (addAll) {
        options[type].push({
            value: '',
            label: utils.i18n('common.text.all')
        });
    }
    for (let key in data) {
        if (options[type]) {
            options[type].push({
                value: key,
                label: data[key],
                key: key // 为element-ui 穿梭框提供唯一标识key字段所加,兼容以前数据处理格式
            });
        }
    }
};
var chanelTransfer = function (options, type, data, addAll) {
    if (addAll) {
        options[type].push({ value: '', label: utils.i18n('common.text.all') });
    }
    for (let key in data) {
        if (options[type]) {
            options[type].push({
                key: key,
                label: data[key]
            });
        }
    }
};
/**
 * 把数据字典里的值设置到selectOpt中
 */
utils.fillSelect = function (keyMap, data, selectOpt, addAll) {
    if (!keyMap) return;
    for (var key in keyMap) {
        _fill(selectOpt, key, data[keyMap[key]], addAll);
    }
};
/**
 * 把数据字典里的值设置到穿梭框中
 */
utils.fillTransfer = function (keyMap, data, selectOpt, addAll) {
    if (!keyMap) return;
    for (var key in keyMap) {
        chanelTransfer(selectOpt, key, data[keyMap[key]], addAll);
    }
};
utils.downloadFile = function (res, fileName, fileType) {
    if (fileName == null) {
        fileName = 'test.doc';
    }
    if (fileType == null) {
        fileType = 'application/msword;charset=utf-8';
    }
    var blob = new Blob([res], {
        type: fileType
    });
    if ('download' in document.createElement('a')) {
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = fileName; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
    } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName);
    }
};

// value->节点id, Key; pvalue->父节点id,
utils.listToTree = function (value, pValue, list) {
    if (!list.length) return list;
    function exists(list, pValue) {
        return list.some((item, index, array) => {
            return item[value] == pValue;
        });
    }
    let nodes = [];
    list.forEach((item, index, array) => {
        if (!exists(array, item[pValue])) nodes.push(item);
    });
    let toDo = [];
    nodes.forEach((item, index, array) => {
        toDo.push(item);
    });
    while (toDo.length) {
        let node = toDo.shift();
        list.forEach((item, index, array) => {
            if (item[pValue] == node[value]) {
                if (node.children) {
                    node.children.push(item);
                } else {
                    node.children = [item];
                }
                toDo.push(item);
            }
        });
        while (toDo.length) {
            let node = toDo.shift();
            list.forEach((item, index, array) => {
                if (item[pValue] == node[value]) {
                    if (node.children) {
                        node.children.push(item);
                    } else {
                        node.children = [item];
                    }
                    toDo.push(item);
                }
            });
            if (node.children) {
                node.children.sort((item1, item2) => {
                    return (item1.orderNo != item2.orderNo ? item1.orderNo - item2.orderNo : item1.authId - item2.authId);
                });
            }
        }
    }
    nodes.forEach(first => {
        if (first.children) {
            for (let i = 0; i < first.children.length;) {
                let child = first.children[i];
                if (child.hideFlag === '1' && child.children) {
                    first.children.splice(i, 1, ...child.children);
                    i += child.children.length;
                } else {
                    i++;
                }
            }
        }
    });
    return nodes;
};
utils.isEmpty = function (value) {
    if (value == null || value == undefined || value == '' || value.length == 0) {
        return true;
    }
    return false;
};
utils.isNotEmpty = function (value) {
    return !this.isEmpty(value);
};
utils.uuid = function () {
    if (this.uuid_) {
        this.uuid_++;
    } else {
        this.uuid_ = +(new Date().getTime() + '').substring(0, 10);
    }
    return this.uuid_;
};
utils.clone = function (obj) {
    return JSON.parse(JSON.stringify(obj));
};
utils.merge = function (dest, origin) {
    _.forEach(dest, (value, key) => {
        if (value === null) {
            dest[key] = origin[key];
        } else if (_.isObject(value) && !_.isArray(value)) {
            this.merge(dest[key], origin[key]);
        }
    });
};
var saveAs = window.saveAs || (function (view) {
    var doc, get_URL, save_link, can_use_save_link, click, is_safari, is_chrome_ios, throw_outside, force_saveable_type, arbitrary_revoke_timeout, revoke, dispatch, auto_bom, FileSaver, FS_proto, saveAs;
    if (void 0 === view || typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) { return; }
    doc = view.document;
    get_URL = function () {
        return view.URL || view.webkitURL || view;
    };
    save_link = doc.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    can_use_save_link = 'download' in save_link;
    click = function (node) {
        var event = new MouseEvent('click');
        node.dispatchEvent(event);
    };
    is_safari = /constructor/i.test(view.HTMLElement) || view.safari;
    is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent);
    throw_outside = function (ex) {
        (view.setImmediate || view.setTimeout)(function () {
            throw ex;
        }, 0);
    };
    force_saveable_type = 'application/octet-stream';
    arbitrary_revoke_timeout = 4e4;
    revoke = function (file) {
        var revoker = function () {
            typeof file === 'string' ? get_URL().revokeObjectURL(file) : file.remove();
        };
        setTimeout(revoker, arbitrary_revoke_timeout);
    };
    dispatch = function (filesaver, event_types, event) {
        var i, listener;
        event_types = [].concat(event_types);
        i = event_types.length;
        for (; i--;) {
            listener = filesaver['on' + event_types[i]];
            if (typeof listener === 'function') {
                try {
                    listener.call(filesaver, event || filesaver);
                } catch (ex) {
                    throw_outside(ex);
                }
            }
        }
    };
    auto_bom = function (blob) {
        if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
            return new Blob([String.fromCharCode(65279), blob], {
                type: blob.type
            });
        }
        return blob;
    };
    FileSaver = function (blob, name, no_auto_bom) {
        var filesaver, type, force, object_url, dispatch_all, fs_error;
        no_auto_bom || (blob = auto_bom(blob));
        filesaver = this;
        type = blob.type;
        force = type === force_saveable_type;
        dispatch_all = function () {
            dispatch(filesaver, 'writestart progress write writeend'.split(' '));
        };
        fs_error = function () {
            var reader, opened;
            if ((is_chrome_ios || force && is_safari) && view.FileReader) {
                reader = new FileReader;
                reader.onloadend = function () {
                    var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
                    view.open(url, '_blank') || (view.location.href = url);
                    url = void 0;
                    filesaver.readyState = filesaver.DONE;
                    dispatch_all();
                };
                reader.readAsDataURL(blob);
                filesaver.readyState = filesaver.INIT;
                return;
            }
            object_url || (object_url = get_URL().createObjectURL(blob));
            if (force) { view.location.href = object_url; } else {
                opened = view.open(object_url, '_blank');
                opened || (view.location.href = object_url);
            }
            filesaver.readyState = filesaver.DONE;
            dispatch_all();
            revoke(object_url);
        };
        filesaver.readyState = filesaver.INIT;
        if (can_use_save_link) {
            object_url = get_URL().createObjectURL(blob);
            setTimeout(function () {
                save_link.href = object_url;
                save_link.download = name;
                click(save_link);
                dispatch_all();
                revoke(object_url);
                filesaver.readyState = filesaver.DONE;
            });
            return;
        }
        fs_error();
    };
    FS_proto = FileSaver.prototype;
    saveAs = function (blob, name, no_auto_bom) {
        return new FileSaver(blob, name || blob.name || 'download', no_auto_bom);
    };
    if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
        return function (blob, name, no_auto_bom) {
            name = name || blob.name || 'download';
            no_auto_bom || (blob = auto_bom(blob));
            return navigator.msSaveOrOpenBlob(blob, name);
        };
    }
    FS_proto.abort = function () { };
    FS_proto.readyState = FS_proto.INIT = 0;
    FS_proto.WRITING = 1;
    FS_proto.DONE = 2;
    FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
    return saveAs;
}(window));

function s2ab(s) {
    var i; var buf = new ArrayBuffer(s.length);


    var view = new Uint8Array(buf);
    for (i = 0; i != s.length; ++i) { view[i] = 255 & s.charCodeAt(i); }
    return buf;
}
utils.exportAsXlsx = function (data, fileName) {
    var wbout; var wb = XLSX.utils.book_new();


    var ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: !1,
        type: 'binary'
    });
    saveAs(new Blob([s2ab(wbout)], {
        type: 'application/octet-stream'
    }), fileName);
};
utils.i18nReplace = function (str, obj) {
    const subRegRex = /\{\s*([^\|\}]+?)\s*(?:\|([^\}]*))?\s*\}/g;
    str = str || '';
    obj = obj || {};
    return str.replace ? str.replace(subRegRex, function (match, key) {
        return obj[key] ? obj[key] : match;
    }) : str;
};
utils.getFormatDate = function (timestamp) {
    if (!timestamp) return null;
    let date = new Date(timestamp);
    return (
        date.getFullYear() +
    '-' +
    (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) +
    '-' +
    (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
    );
};
utils.encode64 = function (input) {
    input = input + '';
    var keyStr = 'ABCDEFGHIJKLMNOP' + 'QRSTUVWXYZabcdef' + 'ghijklmnopqrstuv' + 'wxyz0123456789+/' + '=';
    var output = '';
    var chr1; var chr2; var chr3 = '';
    var enc1; var enc2; var enc3; var enc4 = '';
    var i = 0;
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
      keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = '';
        enc1 = enc2 = enc3 = enc4 = '';
    } while (i < input.length);
    return output;
};
/**
 * 文件上传检查
 *  file 文件上传后回调的file，
 *  params 需要校验的参数
 *  参数示例   {name: ".xlsx,.doc", size: "10"}
 * 默认参数：{ name: ".rar,.zip,.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf",
                size: "10"}
 */
utils.checkFile = function (file, params = {
    name: '.rar,.zip,.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf',
    size: '10'
}, context) {
    let isContainKey = false;
    let result = true;
    for (let key in params) {
        if (file[key]) {
            isContainKey = true;
        }
    }
    if (!isContainKey) {
        throw '请检查传入参数，传入对象必须是file的属性值,目前仅支持 name、size属性,name支持：.xlsx,.doc';
    } else {
        const nameList = params.name.split(',');
        const name = file.name.substring(file.name.lastIndexOf('.'));
        if (nameList.findIndex(e => e == name) == -1) {
            context.$message({
                message: `上传的文件格式必须是${params.name}`,
                type: 'error'
            });
            result = false;
        }
        const outSize = file.size / 1024 / 1024 > params.size * 1;
        if (outSize) {
            context.$message({
                message: `上传的文件大小不能超过${params.size}M`,
                type: 'error'
            });
            result = false;
        }
    }
    return result;
};
//此方法有待于进一步优化，暂时屏蔽
// utils.getIntranetIP = function() {
//     function getIP(callback) {
//         let ipDups = {};
//         let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
//         let servers = { iceServers: [] };
//         let pc = new RTCPeerConnection(servers);
//         function handleCandidate(candidate) {
//             let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
//             let ipAddr = ipRegex.exec(candidate)[1];
//             if(ipDups[ipAddr] === undefined) { callback(ipAddr); }
//             ipDups[ipAddr] = true;
//         }
//         pc.onicecandidate = function(ice) {
//             if (ice.candidate) {
//                 handleCandidate(ice.candidate.candidate);
//             }
//         };
//         pc.createDataChannel('');
//         pc.createOffer(function(result) {
//             pc.setLocalDescription(result, function() {}, function() {});
//         }, function() {});
//         setTimeout(function() {
//             let lines = pc.localDescription.sdp.split('\n');
//             lines.forEach(function(line) {
//                 if(line.indexOf('a=candidate:') === 0) { handleCandidate(line); }
//             });
//         }, 1000);
//     }
//     return new Promise((resolve) => {
//         getIP(function (ip) {
//             resolve(ip);
//         });
//     }).then(res => {
//         return res;
//     });
// };

/**
 * 参数验证
 * @param {*} resouceArray 源数据--字典数组（如：[{label: "A", value: "01"}, {label: "B", value: "02"}]）
 * @param {*} resourceStr 源数据--多选储存字符串(如："A,B")
 * @param {*} key 原数组的键的key（如："label"）
 * @param {*} value 原数组的值的key（如："value"）
 * @returns {Array} 返回解析后的数组（如：'["01", "02"]'）
 */
utils.translateMultiSelect = function (resouceArray, resourceStr, key, value) {
    let targetArr = [];
    if (resourceStr && resourceStr.length > 0 && resouceArray && resouceArray.length > 0) {
        let currentStrArr = resourceStr.split(',');
        resouceArray.map((item) => {
            currentStrArr.map((element) => {
                if (item[key] === element) {
                    targetArr.push(item[value]);
                }
            });
        });
    }
    return targetArr;
}

/**
 * 参数验证
 * @param {*} resouceArray 源数据--字典数组（如：[{label: "A", value: "01"}, {label: "B", value: "02"}]）
 * @param {*} resourceArr 源数据--多选储存key数组(如：["01", "02"]
 * @returns {Array} 返回解析后的数组（如：'A,B'）
 */
utils.translateMultiSelectToStr = function (resouceArray, resourceArr) {
    let targetArr = [];
    if (resourceArr && resourceArr.length > 0 && resouceArray && resouceArray.length > 0) {
        resouceArray.map((item) => {
            resourceArr.map((element) => {
                if (item.value === element) {
                    targetArr.push(item.label);
                }
            });
        });
    }
    return targetArr.join(',');
}

/**
 * 参数验证
 * @param {*} dicArray 源数据--字典数组（如：[{label: "A", value: "01"}, {label: "B", value: "02"}]）
 * @param {*} dicValue 数组中的值（如："01"）
 * @param {*} key 原数组的键的key（如："label"）
 * @param {*} value 原数组的值的key（如："value"）
 * @returns {String} 返回文字（如："A"）
 */
utils.translateLabel = function (dicArray, dicValue, key, value) {
    let label = '';
    for (let i = 0; i < dicArray.length; i++) {
      if (dicArray[i][key] === dicValue) {
        label = dicArray[i][value];
      }
    }
    return label;
}

export default utils;
